from . import api
from .. import db
from .authentication import auth
from ..utils.aliyunVideo import *
from ..utils.checkUpload import *
from ..models import lovePost, userLovePostLike, User, userCollection, image, video as videoModel, follows
from flask import request, jsonify, g, current_app
import traceback, time, base64


# 获取视频播放url
def getVideo(videoId):
    # 从阿里云视频点播服务获取视频的url -- 播放地址
    clt = init_vod_client(current_app.config['ACCESSKEY_ID'], current_app.config['ACCESSKEY_SECRET'])
    playInfo = get_play_info(clt, videoId)
    if playInfo:
        playList = playInfo.get('PlayInfoList').get('PlayInfo')
        playUrl = playList[0].get('PlayURL')
        return playUrl
    else:
        return None

# √
# 表白墙上传,纯文字
@api.route('/lovePostText', methods=['POST'])
def upload_love_post_text():
    # 生成love_post对象，并插入到表中
    love_post = lovePost.from_json(request.json)
    
    try:
        db.session.add(love_post)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        print(e)
        response = jsonify(error='Upload love post failed!', detail=traceback.format_exc())
        response.status_code = 400
        return response
        
    print('[+] add love post: %s' % love_post)
    response = jsonify(message='Upload love post successfully!')
    response.status_code = 200
    return response

# √
# 表白墙上传  图片
@api.route('/lovePostImg', methods=['POST'])
def upload_love_post_img():
    imgUrl, message, status_code = saveImg(request, current_app.config['IMAGES_UPLOAD_FOLDER'])
    
    if status_code == 200: 
        sequence_num = request.form.get('sequence_num') if request.form.get('sequence_num') else 0
        love_post = lovePost.query.get(request.form.get('love_post_id'))
        # 若不存在表白墙记录
        if love_post is None:
            # 若当前图片为第一张，才会新增表白墙记录
                love_post = lovePost(
                    love_post_id=request.form.get('love_post_id'), 
                    user_id=request.form.get('user_id'), 
                    media_type=request.form.get('media_type'), 
                    describe=request.form.get('describe'), 
                    tag=request.form.get('tag')
                )
                
                try:
                    db.session.add(love_post)
                    db.session.commit()
                    print('[+] add love post: %s' % love_post)
                except Exception as e:
                    db.session.rollback()
                    print(e)
                    response = jsonify(error=traceback.format_exc())
                    response.status_code = 403
                    return response

        img = image(
            love_post_id=love_post.love_post_id, 
            img_url=imgUrl,
            sequence_num=sequence_num
        )
        try:
            db.session.add(img)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            print(e)
            response = jsonify(error=traceback.format_exc())
            response.status_code = 403
            return response
        

        response = jsonify(message='Save img successfully!', imgUrl=imgUrl)
        response.status_code = 200
        return response
    else:
        response = jsonify(error=message)
        response.status_code = status_code
        return response

# √
# 上传表白墙 视频
@api.route('/lovePostVideo', methods=['POST'])
def upload_love_post_video():
    if 'video' not in request.files:
        return jsonify(error="No file part")
    video = request.files['video']

    if video.filename == '':
        return jsonify(error='No selected file')

    if video and allowed_video_file(video.filename):
        # 在本地保存视频
        filename = datetime.now().strftime('%Y%m%d%H%M%S_') + random_string() + \
            '_' + secure_filename(video.filename)
        localPath = os.path.join(
            current_app.config['VIDEOS_UPLOAD_FOLDER'], filename)
        video.save(localPath)

        # videoInfo = {}
        # videoInfo['videoTitle'] = filename
        # videoInfo['videoAddress'] = localPath

        # 建立与阿里云服务器的连接
        try:
            # clt = init_vod_client(
            #     current_app.config['ACCESSKEY_ID'], current_app.config['ACCESSKEY_SECRET'])
            # uploadInfo = create_upload_video(clt, videoInfo)
            # 填充字段aliyun_video_id
            aliyun_video_id = uploadLocalVideo(
                current_app.config['ACCESSKEY_ID'], 
                current_app.config['ACCESSKEY_SECRET'],
                localPath
            )
            # 打印aliyun返回的数据
            # print(aliyun_video_id)
            # print(json.dumps(uploadInfo, ensure_ascii=False, indent=4))
        except Exception as e:
            print(e)
            print(traceback.format_exc())
            response = jsonify(error=traceback.format_exc())
            response.status_code = 400
            return response

        print('[+] add love post: %s' % request.form)
        love_post = lovePost(
            love_post_id=request.form.get('love_post_id'), 
            user_id=request.form.get('user_id'), 
            media_type=request.form.get('media_type'), 
            describe=request.form.get('describe'), 
            tag=request.form.get('tag')
        )
        try:
            db.session.add(love_post)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            print(e)
            response = jsonify(error=traceback.format_exc())
            response.status_code = 403
            return response

        v = videoModel(
            love_post_id=love_post.love_post_id, 
            aliyun_video_id=aliyun_video_id
        )

        try:
            db.session.add(v)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            print(e)
            response = jsonify(error=traceback.format_exc())
            response.status_code = 403
            return response

        # 上传成功，删除本地文件
        # if os.path.exists(localPath):
        #     os.remove(localPath)
        response = jsonify(message='Save video successfully!')
        response.status_code = 200
        return response

    response = jsonify(error='No allow upload file type!')
    response.status_code = 403
    return response

# √
# 删除表白墙
@api.route('/lovePost/<lovePostId>', methods=['DELETE'])
def delete_love_post(lovePostId):
    love_post = lovePost.query.get_or_404(lovePostId)
    
    if love_post.user_id != g.current_user.user_id:
        response = jsonify(error="forbidden!", detail="You can't delete other user's lovePost!")
        response.status_code = 403
        return response

    try:
        db.session.delete(love_post)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        print(e)
        response = jsonify(error="Delete love post failed!", detail=traceback.format_exc())
        response.status_code = 404
        return response

    response = jsonify(message='Delete love post: %r successfully!' % lovePostId)
    response.status_code = 200
    return response

# √
# 查看表白墙概览
@api.route('/lovePost', methods=['GET'])
def get_love_posts():
    page = request.args.get("page") if request.args.get("page") else 1
    pageSize = request.args.get("pageSize") if request.args.get("pageSize") else 20
    love_post = lovePost.query.order_by(lovePost.publish_time.desc()).paginate(int(page), int(pageSize), False).items

    if len(love_post) == 0:
        response= jsonify(error='No select data!')
        response.status_code = 404
        return response

    u_collections = userCollection.query.filter_by(user_id=g.current_user.user_id).all()
    u_love_post_like = userLovePostLike.query.filter_by(user_id=g.current_user.user_id).all()

    u_collections = [l.love_post_id for l in u_collections]
    u_love_post_like = [l.love_post_id for l in u_love_post_like]
    # print(u_love_post_like)

    love_posts = [l.to_json() for l in love_post]
    for love_post in love_posts:
        user = User.query.get(love_post['user_id'])
        love_post['nickName'] = user.nickName
        love_post['avatarUrl'] = user.avatarUrl
        
        love_post['is_collected'] = True if love_post['love_post_id'] in u_collections else False
        love_post['is_user_like'] = True if love_post['love_post_id'] in u_love_post_like else False
        
        if love_post['media_type'] == 'img':
            imgs = image.query.filter_by(love_post_id=love_post['love_post_id']).order_by(image.sequence_num).all()
            imgUrls = [i.img_url for i in imgs]
            love_post['imgUrls'] = imgUrls
            love_post['countOfImg'] = len(imgUrls)

        if love_post['media_type'] == 'video':
            v = videoModel.query.filter_by(love_post_id=love_post['love_post_id']).first()
            love_post['videoUrl'] = getVideo(v.aliyun_video_id)

    response = jsonify(message='Get love post data successfully!', lovePost=love_posts)
    response.status_code = 200
    return response


# √
# 查看表白墙关注概览
@api.route('/lovePostFollowed', methods=['GET'])
def get_love_posts_followed():
    page = request.args.get("page") if request.args.get("page") else 1
    pageSize = request.args.get("pageSize") if request.args.get("pageSize") else 20
    follow_user = follows.query.filter_by(fans_id=g.current_user.user_id).all()
    follow_user_id = [u.user_id for u in follow_user]
    love_post = lovePost.query.filter(lovePost.user_id.in_(follow_user_id)).order_by(lovePost.publish_time.desc()).paginate(int(page),int(pageSize),False).items

    if len(love_post) == 0:
        response = jsonify(error='No select data!')
        response.status_code = 404
        return response

    u_collections = userCollection.query.filter_by(user_id=g.current_user.user_id).all()
    u_love_post_like = userLovePostLike.query.filter_by(user_id=g.current_user.user_id).all()

    u_collections = [l.love_post_id for l in u_collections]
    u_love_post_like = [l.love_post_id for l in u_love_post_like]
    # print(u_love_post_like)

    love_posts = [l.to_json() for l in love_post]
    for love_post in love_posts:
        user = User.query.get(love_post['user_id'])
        love_post['nickName'] = user.nickName
        love_post['avatarUrl'] = user.avatarUrl

        love_post['is_collected'] = True if love_post['love_post_id'] in u_collections else False
        love_post['is_user_like'] = True if love_post['love_post_id'] in u_love_post_like else False

        if love_post['media_type'] == 'img':
            imgs = image.query.filter_by(love_post_id=love_post['love_post_id']).order_by(image.sequence_num).all()
            imgUrls = [i.img_url for i in imgs]
            love_post['imgUrls'] = imgUrls
            love_post['countOfImg'] = len(imgUrls)

        if love_post['media_type'] == 'video':
            v = videoModel.query.filter_by(love_post_id=love_post['love_post_id']).first()
            love_post['videoUrl'] = getVideo(v.aliyun_video_id)

    response = jsonify(message='Get love post data successfully!', lovePost=love_posts)
    response.status_code = 200
    return response

# √
# 查看热门表白墙
@api.route('/lovePostHot', methods=['GET'])
def get_love_posts_hot():
    page = request.args.get("page") if request.args.get("page") else 1
    pageSize = request.args.get("pageSize") if request.args.get("pageSize") else 20
    love_post = lovePost.query.order_by(lovePost.review.desc()).paginate(int(page),int(pageSize),False).items

    if len(love_post) == 0:
        response = jsonify(error='No select data!')
        response.status_code = 404
        return response

    u_collections = userCollection.query.filter_by(user_id=g.current_user.user_id).all()
    u_love_post_like = userLovePostLike.query.filter_by(user_id=g.current_user.user_id).all()

    u_collections = [l.love_post_id for l in u_collections]
    u_love_post_like = [l.love_post_id for l in u_love_post_like]
    # print(u_love_post_like)

    love_posts = [l.to_json() for l in love_post]
    for love_post in love_posts:
        user = User.query.get(love_post['user_id'])
        love_post['nickName'] = user.nickName
        love_post['avatarUrl'] = user.avatarUrl

        love_post['is_collected'] = True if love_post['love_post_id'] in u_collections else False
        love_post['is_user_like'] = True if love_post['love_post_id'] in u_love_post_like else False

        if love_post['media_type'] == 'img':
            imgs = image.query.filter_by(love_post_id=love_post['love_post_id']).order_by(image.sequence_num).all()
            imgUrls = [i.img_url for i in imgs]
            love_post['imgUrls'] = imgUrls
            love_post['countOfImg'] = len(imgUrls)

        if love_post['media_type'] == 'video':
            v = videoModel.query.filter_by(love_post_id=love_post['love_post_id']).first()
            love_post['videoUrl'] = getVideo(v.aliyun_video_id)

    response = jsonify(message='Get love post data successfully!', lovePost=love_posts)
    response.status_code = 200
    return response

# √
# 增加表白墙喜欢数
@api.route('/lovePostLike/<lovePostId>', methods=['POST'])
def add_love_post_like(lovePostId):
    u_love_post_like = userLovePostLike(user_id=g.current_user.user_id, love_post_id=lovePostId)
    try:
        db.session.add(u_love_post_like)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        print(e)
        response = jsonify(error="Add like fail!", detail=traceback.format_exc())
        response.status_code = 403
        return response
    
    response = jsonify(message='Add like successfully!')
    response.status_code = 200
    return response

# √
# 减少表白墙喜欢数
@api.route('/lovePostLike/<lovePostId>', methods=['DELETE'])
def del_love_post_like(lovePostId):
    u_love_post_like = userLovePostLike.query.filter(userLovePostLike.user_id==g.current_user.user_id, \
                                                    userLovePostLike.love_post_id==lovePostId).first_or_404()
    try:
        db.session.delete(u_love_post_like)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        print(e)
        response = jsonify(error="Delete like failed!", detail=traceback.format_exc())
        response.status_code = 400
        return response

    response = jsonify(message='Delete like successfully!')
    response.status_code = 200
    return response